package com.nercel.dsj.gksales.api.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.nercel.dsj.gksales.constant.RedisKeyConstent;
import com.nercel.dsj.gksales.exception.ResponseCode;
import com.nercel.dsj.gksales.model.ResponseResult;
import com.nercel.dsj.gksales.model.dto.CouponParamsDTO;
import com.nercel.dsj.gksales.service.CouponService;
import com.nercel.dsj.gksales.util.ApiResultUtil;
import com.nercel.dsj.gksales.util.CommonJudgeUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;

@RestController
@Api(tags = "激活码相关接口")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CouponApiController extends BaseApiController {

    @Autowired
    private CouponService couponService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping(value = "/api/v1/coupon")
    @ApiOperation(value = "联通渠道/教育局官网创建激活码")
    public ResponseResult genCoupon(@ApiParam(value = "参数信息") @RequestBody CouponParamsDTO paramsDTO) {
        if (CommonJudgeUtils.isNullOrEmpty(paramsDTO.getPhone())) {
            return new ResponseResult(ResponseCode.INTERNAL_SERVER_ERROR.getCode(), "手机号不能为空", null);
        }
        if (CommonJudgeUtils.isNullOrEmpty(paramsDTO.getOpenId())) {
            return new ResponseResult(ResponseCode.INTERNAL_SERVER_ERROR.getCode(), "openId不能为空", null);
        }
        String openId = stringRedisTemplate.opsForValue().get(RedisKeyConstent.OPENID + ":" + paramsDTO.getOpenId());
        // redis中此用户的openId已经存在，则表示此微信用户已经申请过激活码，此时用户不能再申请了
        if (openId != null) {
            return new ResponseResult(ResponseCode.INTERNAL_SERVER_ERROR.getCode(), "此微信用户已申请过激活码", null);
        }
        couponService.createActivationCode(paramsDTO);
        return ApiResultUtil.success();
    }

}
